package net.csdra.DongPoShuZiTuShuGuan.service;

import net.csdra.DongPoShuZiTuShuGuan.domain.PlayInfo;
import net.csdra.DongPoShuZiTuShuGuan.domain.PlayInfoRepository;
import net.csdra.DongPoShuZiTuShuGuan.domain.Video;
import net.csdra.DongPoShuZiTuShuGuan.domain.VideoRepository;
import net.csdra.DongPoShuZiTuShuGuan.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Created by add on 2018/1/17.
 */

@Service
public class PlayInfoManagerServiceImpl implements PlayInfoManagerService {
    @Autowired
    PlayInfoRepository playInfoRepository;
    @Autowired
    VideoRepository videoRepository;

    @Override
    public PlayInfo recordingPlayInfo(RecordingPlayInfo recordingPlayInfo) {
        Assert.notNull(recordingPlayInfo, "参数不能为空");
        Assert.hasText(recordingPlayInfo.getVideoUrl(), "@url不能为空");
        Assert.hasText(recordingPlayInfo.getName(), "@资源名称不能为空");
        PlayInfo playInfo = playInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            return criteriaQuery.orderBy(criteriaBuilder.asc(root.get("createTime"))).getRestriction();
        }).get(0);
        if (null == playInfo) {
            playInfo = Utils.createAutoSet(PlayInfo.class, "system");
        }
        Video newVideo = Utils.createAutoSet(Video.class, "system");
        Utils.copy(recordingPlayInfo, newVideo);
        this.videoRepository.save(newVideo);
        playInfo.setVideoId(newVideo.getId());
        playInfoRepository.save(playInfo);
        PlayInfo result = new PlayInfo();
        Utils.copy(playInfo, result);
        return result;
    }

    @Override
    public PlayInfo setPlayInfo(SetPlayInfo setPlayInfo) {
        Assert.notNull(setPlayInfo, "参数不能为空");
        Assert.hasLength(setPlayInfo.getId(), "参数id不能为空");
        Video one = this.videoRepository.findOne(setPlayInfo.getId());
        Assert.notNull(one, "@视频不存在");
        PlayInfo playInfo = playInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            return criteriaQuery.orderBy(criteriaBuilder.asc(root.get("createTime"))).getRestriction();
        }).get(0);
        if (null == playInfo) {
            playInfo = Utils.createAutoSet(PlayInfo.class, "system");
        }
        playInfo.setVideoId(one.getId());
        this.playInfoRepository.save(playInfo);
        PlayInfo result = new PlayInfo();
        Utils.copy(playInfo, result);
        return result;
    }
}
